<%--
  Created by IntelliJ IDEA.
  User: 您的名字
  Version: 1.0
 --%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<html>
<head>
    <title>EasyUI CRUD 示例页面</title>
    <meta charset="UTF-8">
    <base href="<%=request.getContextPath()%>/">
    <!-- 引入 EasyUI 的默认主题样式 -->
    <link rel="stylesheet" type="text/css" href="static/js/easyui/themes/bootstrap/easyui.css">
    <!-- 引入 EasyUI 的图标样式 -->
    <link rel="stylesheet" type="text/css" href="static/js/easyui/themes/icon.css">
    <!-- 引入自定义的公共CSS -->
    <link rel="stylesheet" type="text/css" href="static/css/common.css"/>
    <!-- 引入 EasyUI 默认的 jQuery（无需单独引入 jQuery） -->
    <script src="static/js/easyui/jquery.min.js"></script>
    <!-- 引入 EasyUI 的核心 JS 文件 -->
    <script src="static/js/easyui/jquery.easyui.min.js"></script>
    <!-- 引入 EasyUI 的中文语言包 -->
    <script src="static/js/easyui/locale/easyui-lang-zh_CN.js"></script>
    <!-- 引入自定义的公共脚本 -->
    <script src="static/js/owner/common.js"></script>
    <!-- 引入自定义的公共脚本 -->
    <script src="static/js/owner/dataGrid.js"></script>
    <script src="static/js/owner/moment.min.js"></script>
    <!-- daterangepicker 是一个日期范围选择插件，支持选择开始和结束日期 -->
    <link rel="stylesheet" href="static/css/daterangepicker.css">
    <!-- 引入 daterangepicker 的脚本文件 -->
    <script src="static/js/owner/daterangepicker.js"></script>
</head>
<body>
<div class="easyui-layout" data-options="fit:true">
    <div data-options="region:'north',border:false" style="height:50px;padding:5px;">
        <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-picture" plain="true" onclick="openImageDialog()">生成图片</a>
        <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-video" plain="true" onclick="openVideoDialog()">生成视频</a>
        <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-remove" plain="true" onclick="deleteSelectedMedia()">删除</a>
        <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-clear" plain="true" onclick="batchDeleteMedia()">批量删除</a>
    </div>
    <div data-options="region:'center',border:false">
        <!-- 媒体列表 -->
        <table id="datagrid" class="easyui-datagrid">
            <thead>
                <tr>
                    <th data-options="field:'ck',checkbox:true"></th>
                    <th data-options="field:'id',width:60">ID</th>
                    <th data-options="field:'mediaType',width:80,formatter:formatMediaType">媒体类型</th>
                    <th data-options="field:'prompt',width:200">提示词</th>
                    <th data-options="field:'mediaSize',width:100">媒体尺寸</th>
                    <th data-options="field:'model',width:150">使用模型</th>
                    <th data-options="field:'createTime',width:150,formatter:formatDateTime">创建时间</th>
                    <th data-options="field:'status',width:80,formatter:formatStatus">状态</th>
                    <th data-options="field:'mediaUrl',width:120,formatter:formatPreview">预览</th>
                    <th data-options="field:'action',width:80,formatter:formatAction">操作</th>
                </tr>
            </thead>
        </table>

        <!-- 工具栏 -->
        <div id="mediaToolbar" style="padding:5px;">
            <div style="margin-bottom:5px;">
                <label>媒体类型:</label>
                <select id="searchMediaType" class="easyui-combobox" style="width:100px;">
                    <option value="">全部</option>
                    <option value="1">图片</option>
                    <option value="2">视频</option>
                </select>
                <label>提示词:</label>
                <input id="searchPrompt" class="easyui-textbox" style="width:200px;">
                <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-search" onclick="searchMedia()">搜索</a>
                <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-reload" onclick="resetSearch()">重置</a>
            </div>
        </div>
    </div>
</div>

<!-- 添加图片生成对话框 -->
<div id="imgDlg" class="easyui-dialog" style="width:1000px;height:500px;padding:10px"
    data-options="closed:true,modal:true,border:'thin',buttons:'#img-dlg-buttons'">
    <form id="imgForm" method="post" novalidate>
        <div style="margin-bottom:20px">
            <label>提示词:</label>
            <input class="easyui-textbox" id="prompt" name="prompt" style="width:100%" data-options="multiline:true,height:60">
        </div>
        <div style="margin-bottom:20px">
            <label>图片大小:</label>
            <select class="easyui-combobox" id="image_size" name="image_size" style="width:200px;">
                <option value="1024x1024">1024x1024</option>
                <option value="1024x512">1024x512</option>
                <option value="512x512">512x512</option>
            </select>
        </div>
        <div style="margin-bottom:20px">
            <label>生成数量:</label>
            <input class="easyui-numberbox" id="batch_size" name="batch_size" value="1" data-options="min:1,max:4">
        </div>
        <div id="imageResult" style="text-align:center;margin-top:20px;">
            <!-- 生成的图片将在这里显示 -->
        </div>
    </form>
</div>

<div id="img-dlg-buttons">
    <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-ok" onclick="generateImage()">生成</a>
    <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-cancel" onclick="javascript:$('#imgDlg').dialog('close')">关闭</a>
</div>

<!-- 添加视频生成对话框 -->
<div id="videoDlg" class="easyui-dialog" style="width:1000px;height:500px;padding:10px"
    data-options="closed:true,modal:true,border:'thin',buttons:'#video-dlg-buttons'">
    <form id="videoForm" method="post" novalidate>
        <div style="margin-bottom:20px">
            <label>提示词:</label>
            <input class="easyui-textbox" id="videoPrompt" name="prompt" style="width:100%" data-options="multiline:true,height:60">
        </div>
        <div style="margin-bottom:20px">
            <label>视频时长(秒):</label>
            <input class="easyui-numberbox" id="duration" name="duration" value="3" data-options="min:1,max:10">
        </div>
        <div style="margin-bottom:20px">
            <label>视频尺寸:</label>
            <select class="easyui-combobox" id="video_size" name="video_size" style="width:200px;">
                <option value="1024x576">1024x576</option>
                <option value="768x432">768x432</option>
                <option value="576x324">576x324</option>
            </select>
        </div>
        <div id="videoResult" style="text-align:center;margin-top:20px;">
            <!-- 生成的视频将在这里显示 -->
        </div>
        <div id="videoStatus" style="text-align:center;margin-top:20px;display:none;">
            <div class="easyui-progressbar" style="width:100%;"></div>
            <div id="statusText" style="margin-top:10px;"></div>
        </div>
    </form>
</div>

<div id="video-dlg-buttons">
    <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-ok" onclick="generateVideo()">生成</a>
    <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-cancel" onclick="javascript:$('#videoDlg').dialog('close')">关闭</a>
</div>

<!-- 预览对话框 -->
<div id="previewDlg" class="easyui-dialog" style="width:800px;height:600px;padding:10px"
    data-options="closed:true,modal:true,border:'thin',buttons:'#preview-dlg-buttons'">
    <div id="previewContent" style="text-align:center;"></div>
</div>

<div id="preview-dlg-buttons">
    <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-cancel" onclick="javascript:$('#previewDlg').dialog('close')">关闭</a>
</div>

<!-- 确认删除对话框 -->
<div id="confirmDlg" class="easyui-dialog" style="width:300px;height:150px;padding:10px"
    data-options="closed:true,modal:true,border:'thin',buttons:'#confirm-dlg-buttons'">
    <div style="text-align:center;margin-top:20px;">
        <span id="confirmMessage">确定要删除选中的记录吗？</span>
    </div>
</div>

<div id="confirm-dlg-buttons">
    <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-ok" onclick="confirmDelete()">确定</a>
    <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-cancel" onclick="javascript:$('#confirmDlg').dialog('close')">取消</a>
</div>

<!-- 定义页面脚本 -->
<script type="text/javascript">
    $(function () {
        const pageConfig = {
            url: 'ai/media/list', // 数据源URL
            method: 'get',
            rownumbers: true,
            singleSelect: false, // 允许多选
            pagination: true,
            pageSize: 10,
            toolbar: '#mediaToolbar',
        };
        // 调用公共函数初始化 DataGrid
        initializeDataGrid(pageConfig);
    })
    function openImageDialog() {
        $('#imgDlg').dialog('open').dialog('setTitle', '生成图片').window('center');
        $('#imgForm').form('clear');
        $('#imageResult').empty();
    }

    function generateImage() {
        var formData = {
            prompt: $("#prompt").textbox('getValue'),
            image_size: $("#image_size").combobox('getValue'),
            batch_size: $("#batch_size").numberbox('getValue'),
            num_inference_steps: 20,
            guidance_scale: 7.5,
            model: "Kwai-Kolors/Kolors"
        };

        $.ajax({
            url: 'ai/generate-image',
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(formData),
            success: function(result) {
                if(result.code === 200) {
                    var images = result.extend.image.images;
                    $('#imageResult').empty();
                    images.forEach(function(image) {
                        $('#imageResult').append('<a target="_blank" href="' + image.url + '"><img src="' + image.url + '" style="max-width:100%;margin:10px 0;"></a>');
                    });
                    // 刷新媒体列表
                    $('#datagrid').datagrid('reload');
                } else {
                    $.messager.alert('错误', result.msg || '生成图片失败', 'error');
                }
            },
            error: function() {
                $.messager.alert('错误', '请求失败，请稍后重试', 'error');
            },
            dataType: 'json'
        });
    }

    function openVideoDialog() {
        $('#videoDlg').dialog('open').dialog('setTitle', '生成视频').window('center');
        $('#videoForm').form('clear');
        $('#videoResult').empty();
        $('#videoStatus').hide();
        $('.easyui-progressbar').progressbar('setValue', 0);
        $('#statusText').text('');
    }

    function generateVideo() {
        var formData = {
            prompt: $("#videoPrompt").textbox('getValue'),
            duration: $("#duration").numberbox('getValue'),
            video_size: $("#video_size").combobox('getValue'),
            model: "Lightricks/LTX-Video"
        };

        $('#videoStatus').show();
        $('#statusText').text('正在提交视频生成请求...');

        $.ajax({
            url: 'ai/generate-video',
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(formData),
            success: function(result) {
                if(result.code === 200) {
                    var requestId = result.extend.requestId;
                    $('#statusText').text('视频生成中，请稍候...');
                    checkVideoStatus(requestId);
                } else {
                    $.messager.alert('错误', result.msg || '视频生成请求失败', 'error');
                }
            },
            error: function() {
                $.messager.alert('错误', '请求失败，请稍后重试', 'error');
            },
            dataType: 'json'
        });
    }

    function checkVideoStatus(requestId) {
        var checkInterval = setInterval(function() {
            $.ajax({
                url: 'ai/check-video-status',
                method: 'POST',
                contentType: 'application/json',
                data: JSON.stringify({requestId: requestId}),
                success: function(result) {
                    if(result.code === 200) {
                        var status = result.extend.status;
                        if(status.status === 'Succeed') {
                            clearInterval(checkInterval);
                            $('.easyui-progressbar').progressbar('setValue', 100);
                            $('#statusText').text('视频生成完成！');
                            if(status.results && status.results.videos && status.results.videos.length > 0) {
                                $('#videoResult').html('<video controls style="max-width:100%;"><source src="' + status.results.videos[0].url + '" type="video/mp4">您的浏览器不支持视频播放。</video>');
                                // 刷新媒体列表
                                $('#datagrid').datagrid('reload');
                            } else {
                                $('#statusText').text('视频生成失败：未获取到视频URL');
                                $.messager.alert('错误', '视频生成失败：未获取到视频URL', 'error');
                            }
                        } else if(status.status === 'InProgress') {
                            $('.easyui-progressbar').progressbar('setValue', 50);
                            $('#statusText').text('视频正在生成中，请稍候...');
                        } else {
                            clearInterval(checkInterval);
                            $('#statusText').text('视频生成失败');
                            $.messager.alert('错误', '视频生成失败：' + (status.reason || '未知错误'), 'error');
                            // 刷新媒体列表
                            $('#datagrid').datagrid('reload');
                        }
                    }
                },
                error: function() {
                    clearInterval(checkInterval);
                    $('#statusText').text('检查状态失败');
                    $.messager.alert('错误', '检查视频状态失败', 'error');
                },
                dataType: 'json'
            });
        }, 5000); // 每5秒检查一次状态
    }

    // 格式化媒体类型
    function formatMediaType(value) {
        if (value === 1) {
            return '<span style="color:blue;">图片</span>';
        } else if (value === 2) {
            return '<span style="color:green;">视频</span>';
        }
        return value;
    }

    // 格式化状态
    function formatStatus(value) {
        if (value === 0) {
            return '<span style="color:orange;">处理中</span>';
        } else if (value === 1) {
            return '<span style="color:green;">成功</span>';
        } else if (value === 2) {
            return '<span style="color:red;">失败</span>';
        }
        return value;
    }

    // 格式化日期时间
    function formatDateTime(value) {
        if (value) {
            return moment(value).format('YYYY-MM-DD HH:mm:ss');
        }
        return '';
    }

    // 格式化预览
    function formatPreview(value, row) {
        if (value) {
            if (row.mediaType === 1) {
                return '<a href="javascript:void(0)" onclick="previewMedia(\'' + value + '\', 1)">预览图片</a>';
            } else if (row.mediaType === 2) {
                return '<a href="javascript:void(0)" onclick="previewMedia(\'' + value + '\', 2)">预览视频</a>';
            }
        }
        return '无预览';
    }

    // 格式化操作列
    function formatAction(value, row) {
        return '<a href="javascript:void(0)" onclick="deleteMedia(' + row.id + ')">删除</a>';
    }

    // 预览媒体
    function previewMedia(url, type) {
        $('#previewDlg').dialog('open').dialog('setTitle', type === 1 ? '图片预览' : '视频预览').window('center');
        if (type === 1) {
            $('#previewContent').html('<img src="' + url + '" style="max-width:100%;max-height:500px;">');
        } else {
            $('#previewContent').html('<video controls style="max-width:100%;max-height:500px;"><source src="' + url + '" type="video/mp4">您的浏览器不支持视频播放。</video>');
        }
    }

    // 搜索媒体
    function searchMedia() {
        $('#datagrid').datagrid('load', {
            mediaType: $('#searchMediaType').combobox('getValue'),
            prompt: $('#searchPrompt').textbox('getValue')
        });
    }

    // 重置搜索
    function resetSearch() {
        $('#searchMediaType').combobox('setValue', '');
        $('#searchPrompt').textbox('setValue', '');
        $('#datagrid').datagrid('load', {});
    }

    // 删除单个媒体
    function deleteMedia(id) {
        $.messager.confirm('确认', '确定要删除这条记录吗？', function(r) {
            if (r) {
                $.ajax({
                    url: 'ai/media/delete',
                    method: 'POST',
                    data: {id: id},
                    success: function(result) {
                        if (result.code === 200) {
                            $.messager.show({
                                title: '成功',
                                msg: '删除成功',
                                timeout: 2000,
                                showType: 'slide'
                            });
                            $('#datagrid').datagrid('reload');
                        } else {
                            $.messager.alert('错误', result.msg || '删除失败', 'error');
                        }
                    },
                    error: function() {
                        $.messager.alert('错误', '请求失败，请稍后重试', 'error');
                    }
                });
            }
        });
    }

    // 删除选中的媒体
    function deleteSelectedMedia() {
        var row = $('#datagrid').datagrid('getSelected');
        if (row) {
            deleteMedia(row.id);
        } else {
            $.messager.alert('提示', '请选择要删除的记录', 'info');
        }
    }

    // 批量删除变量
    var selectedIds = [];

    // 批量删除媒体
    function batchDeleteMedia() {
        var rows = $('#datagrid').datagrid('getSelections');
        if (rows.length > 0) {
            selectedIds = rows.map(function(row) {
                return row.id;
            });

            $('#confirmMessage').text('确定要删除选中的 ' + rows.length + ' 条记录吗？');
            $('#confirmDlg').dialog('open').dialog('setTitle', '批量删除确认').window('center');
        } else {
            $.messager.alert('提示', '请选择要删除的记录', 'info');
        }
    }

    // 确认删除
    function confirmDelete() {
        if (selectedIds.length > 0) {
            $.ajax({
                url: 'ai/media/batchDelete',
                method: 'POST',
                traditional: true, // 必须设置为true，否则数组参数会被序列化为ids[]=1&ids[]=2的形式
                data: {
                    'ids[]': selectedIds
                },
                success: function(result) {
                    if (result.code === 200) {
                        $.messager.show({
                            title: '成功',
                            msg: '批量删除成功',
                            timeout: 2000,
                            showType: 'slide'
                        });
                        $('#datagrid').datagrid('reload');
                        $('#confirmDlg').dialog('close');
                    } else {
                        $.messager.alert('错误', result.msg || '批量删除失败', 'error');
                    }
                },
                error: function() {
                    $.messager.alert('错误', '请求失败，请稍后重试', 'error');
                }
            });
        }
    }
</script>
</body>
</html>
